﻿Ext.data.Batch = Ext.extend(Ext.util.Observable, {

    autoStart: false,


    current: -1,


    total: 0,


    isRunning: false,


    isComplete: false,


    hasException: false,


    pauseOnException: true,

    constructor: function (config) {
        this.addEvents(

          'complete',


          'exception',


          'operationcomplete',


          'operation-complete'
        );

        Ext.data.Batch.superclass.constructor.call(this, config);


        this.operations = [];
    },


    add: function (operation) {
        this.total++;

        operation.setBatch(this);

        this.operations.push(operation);
    },


    start: function () {
        this.hasException = false;
        this.isRunning = true;

        this.runNextOperation();
    },


    runNextOperation: function () {
        this.runOperation(this.current + 1);
    },


    pause: function () {
        this.isRunning = false;
    },


    runOperation: function (index) {
        var operations = this.operations,
            operation = operations[index];

        if (operation == undefined) {
            this.isRunning = false;
            this.isComplete = true;
            this.fireEvent('complete', this, operations[operations.length - 1]);
        } else {
            this.current = index;

            var onProxyReturn = function (operation) {
                var hasException = operation.hasException();

                if (hasException) {
                    this.hasException = true;
                    this.fireEvent('exception', this, operation);
                } else {


                    this.fireEvent('operation-complete', this, operation);

                    this.fireEvent('operationcomplete', this, operation);
                }

                if (hasException && this.pauseOnException) {
                    this.pause();
                } else {
                    operation.setCompleted();

                    this.runNextOperation();
                }
            };

            operation.setStarted();

            this.proxy[operation.action](operation, onProxyReturn, this);
        }
    }
});